package bootstrap

import (
	"encoding/json"
	"fmt"
	"peilian-api/app/global/common"
	"peilian-api/app/global/databases/tables"
	"peilian-api/app/global/errors"
	"peilian-api/app/global/variable"
	"peilian-api/app/model"
	"strconv"
)

type Cariterias struct {
	CareerId int    `json:"career_id"`
	Criteria string `json:"criteria"`
	Level    string `json:"level"`
}

func loadDataToRedis() error {
	// 初始化学校到数据表
	var num int64
	variable.DB.MySQL.Model(&tables.School{}).Count(&num)
	if num == 0 {
		var allS []*tables.School
		for _, s := range common.SchoolList {
			allS = append(allS, &tables.School{Name: s.(string)})
		}
		variable.DB.MySQL.Model(&tables.School{}).CreateInBatches(allS, len(allS))
	}
	// 将学校信息初始化到redis
	if err := variable.DB.Redis.SAdd(common.RedisSchoolKey, common.SchoolList...); err.Err() != nil {
		return fmt.Errorf(errors.LoadDataToCacheIsFail)
	}

	// 将数据吃初始化到redis
	var questions []tables.SpecialQuestion
	d := variable.DB.MySQL.Model(&tables.SpecialQuestion{}).Where("level = ?", "基础").Group("career_id,level,front_show_tag").Order("front_show_tag desc").Find(&questions)
	if d.Error != nil {
		return fmt.Errorf("failed to load data to redis:%w", d.Error)
	}
	var cariterias []Cariterias
	for _, q := range questions {
		cariterias = append(cariterias, Cariterias{CareerId: int(q.CareerID), Criteria: q.Criteria, Level: q.Level})
	}
	b, err := json.Marshal(cariterias)
	if err != nil {
		return fmt.Errorf("failed to load data to redis:%w", d.Error)
	}
	if err := variable.DB.Redis.Set(common.RedisCriteriaKey, string(b), -1); err.Err() != nil {
		return fmt.Errorf(errors.LoadDataToCacheIsFail)
	}

	// 将申请的信息加载到redis
	var commonConf []tables.CommonConf
	d = variable.DB.MySQL.Model(&tables.CommonConf{}).Where("conf_key='token'").Find(&commonConf)
	if d.Error != nil {
		return fmt.Errorf("failed to load data to redis:%w", d.Error)
	}
	if len(commonConf) == 0 {
		return nil
	}
	var tokenMap map[string]model.AppSecretToken
	tokenMap = make(map[string]model.AppSecretToken, 0)
	for i := 0; i < len(commonConf); i++ {
		uid, _ := strconv.Atoi(commonConf[i].Remarks)
		tokenMap[commonConf[i].ConfValue] = model.AppSecretToken{AppSecret: commonConf[i].ExtendInfo, ClientId: commonConf[i].ConfValue, Source: commonConf[i].Other, Uid: uint(uid)}
	}
	b, _ = json.Marshal(tokenMap)
	if err := variable.DB.Redis.Set(common.RedisTokenKey, string(b), -1); err.Err() != nil {
		return fmt.Errorf(errors.LoadDataToCacheIsFail)
	}
	return nil
}
